package com.cskaoyan.market.util;

import org.apache.ibatis.session.SqlSession;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactory {
    public static Object getProxyInstance(Object target) {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Field[] fields = target.getClass().getDeclaredFields();
                SqlSession session = MybatisUtils.getSession();
                for (Field f : fields) {
                    if (f.getName().endsWith("Mapper")) {
                        f.setAccessible(true);
                        f.set(target, session.getMapper(f.getType()));
                    }
                }
                Object invoke = method.invoke(target, args);
                session.commit();
                session.close();
                return invoke;

            }
        });
    }
}
